<template>
  <div class="character">
    <div class="main">
      <div class="allsearch">
        <section class="search-content">
          <el-row style="width:100%;">
            <el-col :span="14">
              <el-input
                v-model="listQuery.name"
                style="width:40%;"
                placeholder="关键词"
                @keyup.enter.native="resourceHandleFilter"
              />
              <el-button type="primary" size="medium" @click="resourceHandleFilter">搜索</el-button>
              <el-button size="medium" type="info" @click="clearParams">清空</el-button>
            </el-col>
            <el-col :span="10">
              <div style="width:100%">
                <el-button
                  type="primary"
                  size="medium"
                  style="float:right;"
                  @click="addCLick()"
                >新增分校
                </el-button>
              </div>
            </el-col>
          </el-row>
        </section>
      </div>
      <el-dialog :visible.sync="DialogVisible" title="新增分校" width="50%">
        <div class="posterBox">
          <el-form :model="OrganizationVo" label-width="150px" ref="organizationForm">
            <el-form-item label="LOGO">
              <img v-if="OrganizationVo.logoUrl" :src="OrganizationVo.logoUrl" alt class="img" style="width:424px;height:124px;">
              <el-upload
                :on-change="handleLogoChange"
                :http-request="uploadLogoFile"
                :limit="1"
                action=""
                class="upload-demo"
                accept="image/jpg, image/png"
              >
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，建议图片尺寸为250*50，且不超过500kb</div>
                <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="分校名称">
              <el-input v-model="OrganizationVo.orgName" placeholder="请输入标题" style="width:300px"/>
            </el-form-item>
            <el-form-item label="RR(网校二级域名)">
              <el-input v-model="OrganizationVo.suffix" placeholder="RR(网校二级域名)" style="width:300px"/>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="OrganizationVo.status">
                <el-radio label="1">开启</el-radio>
                <el-radio label="0">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button @click="DialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="createData()">保 存</el-button>
      </span>
      </el-dialog>

      <el-dialog :visible.sync="handleCreate" title="创建管理员" width="50%">
        <div class="posterBox">
          <el-form :model="UserAccountVo" label-width="150px" ref="userAccountForm">
            <el-form-item label="账号">
              <el-input v-model="UserAccountVo.account" placeholder="请输入账号" style="width:300px"/>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="UserAccountVo.password" placeholder="请输入密码" style="width:300px" type="password"/>
            </el-form-item>
            <el-form-item label="确认密码">
              <el-input v-model="UserAccountVo.passwordConfirm" placeholder="请输入缺认密码" style="width:300px" type="password"/>
            </el-form-item>
            <el-form-item label="是否禁用">
              <el-radio-group v-model="UserAccountVo.enable">
                <el-radio label="1">开启</el-radio>
                <el-radio label="0">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button @click="handleCreate = false">取 消</el-button>
        <el-button type="primary" @click="createUserAccount(createRow)">保 存</el-button>
      </span>
      </el-dialog>

      <!-- 删除 -->
      <el-dialog :visible.sync="handleDelete" width="25%">
        <div style="width:100%;float:left;height:42px;">确定要删除吗?</div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="deleteData(deleteRow)">确定</el-button>
          <el-button @click="handleDelete = false">取消</el-button>
        </div>
      </el-dialog>
      <!-- 删除 -->

      <!-- 初始化数据 -->
      <el-dialog :visible.sync="handleInit" width="25%">
        <div style="width:100%;float:left;height:42px;">确定要初始化数据吗?</div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="initData(initRow)">确定</el-button>
          <el-button @click="handleInit = false">取消</el-button>
        </div>
      </el-dialog>
      <!-- 初始化数据 -->

      <el-table
        :table-label="tableLabel"
        :table-data="listFilter.slice((currentpage-1)*pagesize,currentpage*pagesize)"
        :list-loading="listLoading"
      >
        <el-table-column slot="button" :min-width="2" label="操作" prop="manage" align="center">
          <template slot-scope="scope">
            <el-button @click="updateCLick(scope.row)" type="primary" title='修改' icon="el-icon-edit" circle></el-button>
            <el-button @click="initCLick(scope.row)" type="primary" title='初始化数据' icon="el-icon-setting" circle></el-button>
            <el-button @click="createCLick(scope.row)" type="primary" title='创建管理员' icon="el-icon-user" circle></el-button>
            <el-button @click="setTenantId(scope.row)" type="primary" title='跳转到分校网站' icon="el-icon-view" circle></el-button>
            <el-button @click="goCampus(scope.row)" type="primary" title='跳转到分校后台' icon="el-icon-search" circle></el-button>
            <el-button @click="deleteCLick(scope.row)" type="danger" title='删除' icon="el-icon-delete" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        :current-page="currentpage"
        :page-size="pagesize"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
  import ElTable from '@/components/Eltable'
  import { scrollTo } from '@/utils/scrollTo' // 上下滑动组件
  import Pagination from '@/components/Pagination' // 分页组件
  import { add, createUserAccount, deleteOrg, getUserAccount, init, list, listCampus } from '@/api/campus/campus' // 数据接口
  import { upLoadFile } from '@/api/upLoadFile' // 数据接口
  import { getTenantId } from '@/utils/auth'

  export default {
    components: {
      ElTable,
      Pagination
    },
    data() {
      return {
        tenantId: '',
        logofile: '',
        OrganizationVo: {
          orgName: '',
          status: '1',
          logoUrl: '',
          suffix: '',
          code: '',
          tenantId: ''
        },
        userInfo: {
          username: '',
          password: ''
        },
        UserAccountVo: {
          account: '',
          logoUrl: '',
          password: '',
          passwordConfirm: '',
          orgId: '',
          enable: '1'
        },
        formLabelWidth: '135px',
        DialogVisible: false,//新增
        handleEdit: false,//编辑
        handleCreate: false,//创建管理员
        handleInit: false,//初始化数据
        handleDelete: false,//删除
        deleteRow: '',
        initRow: '',
        createRow: '',
        deleteCLick(row) {
          this.handleDelete = true
          this.deleteRow = row
        },
        // 列表编辑按钮
        addCLick() {
          this.DialogVisible = true
          this.OrganizationVo = {}
        },
        // 列表编辑按钮
        updateCLick(row) {
          this.DialogVisible = true
          this.OrganizationVo = Object.assign({}, row)
        },
        //创建管理员
        createCLick(row) {
          this.handleCreate = true
          this.createRow = row
          this.getUserAccount(this.createRow.id)
        },
        // 初始化数据
        initCLick(row) {
          this.handleInit = true
          this.initRow = row
        },
        setTenantId(row) {
          this.tenantId = row.tenantId
          if (row.domainName) {
            window.open('http://' + row.domainName + '/eduxcloud/eduIndexAction!goIndex.action?tenantId=' + this.tenantId, '_blank')
          } else {
            this.$message.error('域名不能为空!')
          }
        },
        goCampus(row) {
          getUserAccount(row.id).then(response => {
            this.UserAccountVo = response.data
            if (this.UserAccountVo.account && this.UserAccountVo.password) {
              this.userInfo.username = this.UserAccountVo.account
              this.userInfo.password = this.UserAccountVo.password
              this.userInfo.logoUrl = this.UserAccountVo.logoUrl
              this.$store.dispatch('Login', this.userInfo).then(() => {
                this.$router.push({ path: '/' })
              }).catch(() => {
              })
            } else {
              window.open('http://39.106.22.65', '_blank')
            }
          })
        },
        total: 0,
        currentpage: 1,
        pagesize: 10,
        tableLabel: [
          {
            label: '名称', width: '2', prop: 'orgName'
          }, {
            label: '域名', width: '2', prop: 'domainName', isOpera: true
          }, {
            label: '创建时间', width: '2', prop: 'createTimeTimeStr'
          }
        ],
        listFilter: [],
        listLoading: false,
        listQuery: {
          name: '' // 名称
        }
      }
    },
    mounted() {
      this.getData()
    },
    methods: {
      //接口获取数据
      getData() {
        this.listLoading = true
        list(getTenantId()).then(response => {
          this.total = response.data.items.length
          this.listFilter = response.data.items
          this.listLoading = false
        })
      },
      getUserAccount(orgId) {
        getUserAccount(orgId).then(response => {
          this.UserAccountVo = response.data
        })
      },
      // 数据检索
      resourceHandleFilter() {
        this.listCampus()
      },
      listCampus() {
        this.listLoading = true
        listCampus(getTenantId(), this.listQuery.name).then(response => {
          this.total = response.data.items.length
          this.listFilter = response.data.items
          this.listLoading = false
        })
      },
      clearParams() {
        this.listQuery.name = ''
        this.getData()
      },
      handleClick() {
      },
      handleLogoChange(file) {
        this.logofile = file.raw
      },
      uploadLogoFile() {
        const fileForm = new FormData()
        fileForm.append('name', this.logofile.name)
        fileForm.append('uid', this.logofile.uid)
        fileForm.append('file', this.logofile)
        upLoadFile(fileForm).then(response => {
          this.OrganizationVo.logoUrl = response.data.url
        })
      },

      handleSizeChange(val) {
        this.currentpage = 1
        this.pagesize = val.value
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleCurrentChange(val) {
        this.currentpage = val.value
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      createData() {
        this.$refs['organizationForm'].validate((valid) => {
          if (valid) {
            this.OrganizationVo.tenantId = getTenantId()
            add(this.OrganizationVo).then(() => {
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              setTimeout(function() {
              }, 150)
              this.getData()
              this.$refs['organizationForm'].resetFields()
            })
          }
          this.DialogVisible = false
        })
      },
      createUserAccount(row) {
        this.$refs['userAccountForm'].validate((valid) => {
          if (valid) {
            this.UserAccountVo.tenantId = getTenantId()
            this.UserAccountVo.orgId = row.id
            createUserAccount(this.UserAccountVo).then(() => {
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              setTimeout(function() {
              }, 150)
              this.getData()
              this.$refs['userAccountForm'].resetFields()
            })
          }
          this.handleCreate = false
        })
      },
      deleteData(row) {
        this.handleDelete = false
        deleteOrg(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getData()
        })
      },
      initData(row) {
        this.handleInit = false
        init(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '数据初始化成功',
            type: 'success',
            duration: 2000
          })
          this.getData()
        })
      }
    }
  }
</script>

<style lang="scss">
  .character {
    .main {
      padding: 0 20px;
    }

    .allsearch {
      margin-top: 14px;
      padding: 0;

      .search-content {
        width: 100%;
      }
    }

    .el-dialog {
      border-radius: 5px;
      overflow: hidden;
    }
  }
</style>
